from django.shortcuts import render
from random import randint
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, UpdateAPIView, RetrieveAPIView
from rest_framework.response import Response
from django_redis import get_redis_connection
from meiduo_mall.libs.yuntongxun.sms import CCP
from threading import Thread
from users.serializers import UpdatePasswordSerializer, UserSerializers, UserShowSerializers
from users.models import User
from celery_tasks.sms_code.tasks import send_sms_code


# Create your views here.
# def send_sms_code(mobile, sms_code):
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)


class SMS_Code_View(APIView):
    def get(self, request, mobile):
        # 1.获取前端传递手机号（url已获取）
        # 2.验证手机号格式（url已验证）

        # 3.建立连接 判断前端的请求时间间隔是否在60秒之内
        conn = get_redis_connection('sms_code')
        flag = conn.get('sms_code_flag_%s' % mobile)
        if flag:
            return Response({'error': '请求过于频繁'}, status=403)

        # 4.生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        # 生成管道（用于写入redis数据）
        pl = conn.pipeline()
        # 5.保存短信（redis中）
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        # 生成一个标志数据
        pl.setex('sms_code_flag_%s' % mobile, 60, 2)
        # 将指令通过管道传递给redis
        pl.execute()
        # 6.发送短信(耗时任务, 进行异步执行)
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'], 1)

        # 异步方式１
        # t = Thread(target=send_sms_code, kwargs={'mobile': mobile, 'sms_code': sms_code})
        # t.start()

        # 异步方式２，使用celery
        send_sms_code.delay(mobile, sms_code)
        # 7.结果返回
        return Response('ok')


class UserNameView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return Response({'count': count})


class MobileView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return Response({'count': count})


class UserView(CreateAPIView):
    serializer_class = UserSerializers
    queryset = User.objects.all()


class UserShowView(RetrieveAPIView):
    """
        展示用户信息
    """
    serializer_class = UserShowSerializers
    queryset = User.objects.all()
    # 重写get_object对象
    def get_object(self):
        return self.request.user

class PassInfo(UpdateAPIView):
    serializer_class = UpdatePasswordSerializer
    queryset = User.objects.all()
